package com.jiangyg.mall.authz.controller;

import com.jiangyg.mall.authz.constant.AuthzConstant;
import com.jiangyg.mall.authz.constant.SecurityConstant;
import com.jiangyg.mall.authz.support.authentication.admin.AdminRequestMatcher;
import com.jiangyg.mall.authz.support.authentication.member.MemberRequestMatcher;
import com.jiangyg.mall.core.constant.HttpConstant;
import com.jiangyg.mall.core.support.restful.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 类描述：安全认证控制器
 *
 * @author jiangyg
 * @date 2022-09-01
 */
@Slf4j
@RestController
public class AuthzController {

    /**
     * 后台管理请求匹配器
     */
    private AdminRequestMatcher adminRequestMatcher = new AdminRequestMatcher();

    /**
     * 会员请求匹配器
     */
    private MemberRequestMatcher memberRequestMatcher = new MemberRequestMatcher();

    /**
     * 功能描述：校验请求
     * <p>请求至此，说明已经校验通过</p>
     * <p>如果请求存在认证信息则返回</p>
     *
     * @param path         请求地址
     * @param attachParams 附加参数
     * @return 结果
     */
    @PostMapping(value = "authentication", headers = HttpConstant.CONTENT_TYPE_JSON)
    public Result<String> authentication(HttpServletRequest request,
                                         @RequestParam("path") String path,
                                         @RequestBody Map<String, Object> attachParams) {
        Object authInfo = request.getAttribute(SecurityConstant.AUTH_INFO_ATTR_NAME);
        if (authInfo != null) {
            return Result.ok(authInfo.toString());
        }
        return Result.ok();
    }

    /**
     * 功能描述：获取用户信息
     * @param request 请求
     * @return 用户信息
     */
    @ResponseBody
    @GetMapping(value = "user-info")
    public Result<Object> userInfo(HttpServletRequest request) {
        // 获取会员的用户信息
        if (memberRequestMatcher.matches(request)) {
            final Object memberInfo = request.getSession().getAttribute(AuthzConstant.MEMBER_INFO_SESSION_ID);
            if (memberInfo != null) {
                return Result.ok(memberInfo);
            }
        }
        // TODO 暂不支持 admin 的用户信息获取
        return Result.instance("421");
    }

}
